# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://dzz.juecetou.com/api/Recharge/pay.html'
_QUERY_GATEWAY = 'http://dzz.juecetou.com/api/Query_Order/api_query_order.html'

APP_CONF = {
    'KS_136': {  # 亿来支付 支付宝 3.5% 200-5000 dwc
        'API_KEY': '9cf3833da47bf7ddcef02dc7d54de1ac'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_charge_sign(parameter, key):
    '''  生成下单签名 '''
    s = '{}{}{}{}{}'.format(
        parameter['appid'], parameter['orderid'], parameter['fee'],
        parameter['tongbu_url'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    _LOGGER.info(u'yilaipay sign str: %s, sign:%s', s, sign)
    return sign


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def _get_pay_type(service):
    if service == 'alipay':
        return 'pay_alipay'
    elif service == 'wechat':
        return 'pay_weixin'
    return 'pay_alipay'


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("langlangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='get'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('order_num', pay.id),
        ('pay_amount', str(int(pay_amount * 100))),
        ('notify_url', '{}/pay/api/{}/yilaipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/yilaipay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('ext', 'charge'),
        ('pay_type', _get_pay_type(service)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("yilaipay create charge data: %s, order_id is: %s", json.dumps(parameter_dict),
                 pay.id)
    html_text = _build_form(parameter_dict, _GATEWAY)
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info("yilaipay create data: %s, %s", json.dumps(parameter_dict), url)
    return {'charge_info': url}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("yilaipay notify data: %s, order_id is: %s", data, data['order_num'])
    api_key = _get_api_key(app_id)
    verify_sign(data, api_key)
    pay_id = data['order_num']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, orderid not exists, data: %s", data)
        raise ParamError('yilaipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = str(data['pay_status'])
    mch_id = pay.mch_id
    trade_no = data['trade_no']
    total_fee = float(data['pay_amount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('yilaipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('order_num', pay_order.id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("yilaipay query charge data: %s, order_id is: %s", json.dumps(parameter_dict),
                 pay_id)
    query_gate_url = '{}?mch_id={}&order_num={}&sign={}'.format(_QUERY_GATEWAY,
                                                          app_id, pay_order.id, parameter_dict['sign'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.get(query_gate_url, headers=headers, timeout=3)
    _LOGGER.info("yilaipay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['pay_status'])
        trade_no = str(data['trade_no'])
        total_fee = float(data['pay_amount']) / 100.0
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 1:成功，2:处理中，3:失败
        if trade_status == '1':
            _LOGGER.info('yilaipay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('yilaipay data error, status_code: %s', response.status_code)
